package com.xexun.gpstracker.common;

import java.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import com.xexun.gpstracker.AppManager;
import com.xexun.gpstracker.ui.LoadingActivity;
import com.xexun.gpstracker.ui.SendErrorActivity;
import com.xexun.gpstracker.util.Utils;

/**
 * Created by Admin on 2015/9/23 0023.
 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";

    //系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    //CrashHandler实例
    private static CrashHandler INSTANCE = new CrashHandler();
    //程序的Context对象
    private Context mContext;
    //用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();
    public static final String FILE_EXT = ".properties";
    public static final String BASE_PATH = Utils.getAvailableStoragePath() + "crashLog/";

    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {

    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        Log.e(CrashHandler.class.getName(), "捕获线程异常，线程：" + thread.toString(), ex);
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            AppManager.getAppManager().AppExit();
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //收集设备参数信息
        collectDeviceInfo(mContext);
        //保存日志文件
        final String exFileName = saveCrashInfo2File(ex);
        mContext.startActivity(new Intent(mContext, LoadingActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        Intent intent = new Intent(mContext, SendErrorActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("msg", exFileName);
        mContext.startActivity(intent);
        return true;
    }

    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        //设定所需的信息字段
        String saveMsg = "FINGERPRINT,HARDWARE,BOARD,PRODUCT,DISPLAY,DEVICE," +
                "TAGS,MODEL,BOOTLOADER,CPU_ABI,CPU_ABI2,IS_DEBUGGABLE," +
                "ID,SERIAL,MANUFACTURER,BRAND,TYPE";
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionname", versionName);
                infos.put("versioncode", versionCode);
                infos.put("android_version", android.os.Build.VERSION.RELEASE);
                infos.put("package", pi.packageName);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                String name = field.getName();
                if (!saveMsg.contains(name)) {
                    continue;
                }
                String lowName = name.toLowerCase();
                infos.put(lowName, field.get(null).toString());
                Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e(TAG, "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key).append('=').append(value).append('\n');
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        String causedby = "exception=" + result.replaceAll("\\r?\\n", "|||");
        sb.append(causedby).append('\n');
        FileOutputStream fos = null;
        String fileName = System.currentTimeMillis() + FILE_EXT;
        try {
            File dir = new File(BASE_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            fos = new FileOutputStream(BASE_PATH + fileName);
            fos.write(sb.toString().getBytes());
            return fileName;
        } catch (FileNotFoundException ef) {
            Log.w(TAG, "Could not find files: " + BASE_PATH + fileName);
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    //
                }
            }
        }
        return null;
    }
}
